import { PlusOutlined } from '@ant-design/icons';
import { Button, DatePicker, Input, InputRef, message, Select } from 'antd';
import { memo, useEffect, useMemo, useRef, useState } from 'react';
import '../../styles/metadata.scss';
import datasetService from '@/api/services/datasetService';
import { CollectionMetadataType } from '@/types/dataset';
import dayjs, { Dayjs } from 'dayjs';
import knowService from '@/api/services/knowService';
import { SvgIcon } from '@/components/icon';
import { useDatasetStore } from '@/store/datasetStore';

interface Props {
  collectionId: string | undefined;
  metadata: CollectionMetadataType;
  addMetadata: (metadata: CollectionMetadataType) => void;
  removeMetadata: (metadata: CollectionMetadataType) => void;
}

const Metadatas = ({ collectionId, metadata, addMetadata, removeMetadata }: Props) => {
  const [inputVisible, setInputVisible] = useState<boolean>(false);
  const [inputKey, setInputKey] = useState('');
  const [inputValue, setInputValue] = useState('');
  const [metadataType, setMetadataType] = useState('expiredTime');
  const [dateString, setDateString] = useState('');
  const inputKeyRef = useRef<InputRef>(null);
  const inputRef = useRef<InputRef>(null);
  const { datasetStatus } = useDatasetStore();

  console.log(inputVisible, !metadata.expiredTime);

  useEffect(() => {
    if (inputVisible) {
      inputKeyRef.current?.focus();
    }
  }, []);

  const onDateChange = (dateString: string | string[]) => {
    if (!Array.isArray(dateString)) {
      setDateString(dateString);
    }
  };

  const showInput = () => {
    if (datasetStatus === 'upload_publish' || datasetStatus === 'delete_publish') {
      message.warning('请先通过审核');
      return;
    }
    setInputVisible(true);
  };

  const hideInput = () => {
    setInputVisible(false);
    setDateString('');
    setInputKey('');
    setInputValue('');
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setInputValue(e.target.value);
  };
  const handleInputKeyChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setInputKey(e.target.value);
  };

  const addCollectionMetadata = async () => {
    if (!inputKey) {
      message.warning('key不能为空');
      inputKeyRef.current?.focus();
      return false;
    }
    if (!inputKey) {
      message.warning('key不能为空');
      inputRef.current?.focus();
      return false;
    }

    if (!collectionId) {
      return false;
    }
    try {
      const data = {
        ...metadata,
        [inputKey]: inputValue,
      };
      await datasetService.addCollectionMetadata({
        collection_id: collectionId,
        metadata: data,
      });
      if (dateString) {
        await knowService.postUpdateExpired({
          collection_id: collectionId!,
          expired_time: dateString,
        });
      }
      message.success('添加元数据成功');
      return data;
    } catch (error) {
      console.error(error);
      inputKeyRef.current?.focus();
      return false;
    }
  };

  const addEmpireMetadata = async () => {
    if (!dateString) {
      message.warning('过期时间不能为空');
      return false;
    }

    if (!collectionId) {
      return false;
    }
    try {
      const data = {
        ...metadata,
        ['expiredTime']: dateString,
      };
      await datasetService.addCollectionMetadata({
        collection_id: collectionId,
        metadata: data,
      });
      await knowService.postUpdateExpired({
        collection_id: collectionId!,
        expired_time: dateString,
      });
      message.success('更新过期时间成功');
      setDateString('');
      return data;
    } catch (error) {
      console.error(error);
      inputKeyRef.current?.focus();
      return false;
    }
  };

  const delCollectionMetadata = async (key: string) => {
    if (!collectionId) {
      return false;
    }
    try {
      const { [key]: _, ...updatedMetadata } = metadata;
      await datasetService.delCollectionMetadata({
        collection_id: collectionId,
        metadata: [key],
      });
      message.success('删除元数据成功');
      removeMetadata && removeMetadata(updatedMetadata);
      return true;
    } catch (error) {
      console.error(error);
      inputKeyRef.current?.focus();
      return false;
    }
  };

  const handleConfirm = async () => {
    console.log(11111111111111);

    let res: boolean | CollectionMetadataType = false;
    console.log(dateString);

    if (metadataType === 'kv') {
      res = await addCollectionMetadata();
    } else {
      res = await addEmpireMetadata();
    }

    if (res) {
      addMetadata && addMetadata(res);
      setInputVisible(false);
      setInputValue('');
      setInputKey('');
    }
  };

  const metas = useMemo(() => {
    const {
      webPageSelector,
      relatedImgId,
      hashFileBuffers,
      publishTime,
      expiredTime,
      indexes,
      ...filteredObject
    } = metadata;
    return Object.entries(filteredObject).map(([key, value]) => (
      <div
        key={key}
        style={{
          marginTop: '10px',
          width: '100%',
          backgroundColor: '#F2F3F5',
          padding: '10px',
          display: 'flex',
          flexDirection: 'column',
          borderRadius: '6px',
        }}
      >
        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
          <div className="text-[#86909C]">{key}</div>
          <div>
            {!inputVisible && (
              <SvgIcon icon="editdata" className="mr-2" onClick={showInput}></SvgIcon>
            )}
            <SvgIcon
              icon="deledata"
              onClick={() => {
                delCollectionMetadata(key);
              }}
            ></SvgIcon>
          </div>
        </div>
        <div className="mt-2">
          {(() => {
            if (value === null || value === undefined) return '-';
            if (typeof value === 'object') {
              try {
                return JSON.stringify(value);
              } catch {
                return String(value);
              }
            }
            return String(value);
          })()}
        </div>
      </div>
    ));
  }, [metadata]);

  return (
    <>
      <div className="metadata mb-2 flex flex-wrap gap-1">
        <div style={{ width: '100%' }}>
          {metadata.expiredTime && (
            <div
              style={{
                marginTop: '20px',
                width: '100%',
                backgroundColor: '#F2F3F5',
                padding: '10px',
                display: 'flex',
                flexDirection: 'column',
                borderRadius: '6px',
              }}
            >
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <div className="text-[#86909C]">过期时间</div>
                <div>
                  <button
                    type="button"
                    className="mr-2"
                    style={{
                      background: 'none',
                      border: 'none',
                      padding: '0',
                      cursor: 'pointer',
                      display: 'inline-flex',
                      alignItems: 'center',
                    }}
                    onClick={showInput}
                    onKeyDown={(e) => {
                      if (e.key === 'Enter' || e.key === ' ') {
                        e.preventDefault();
                        showInput();
                      }
                    }}
                    aria-label="编辑过期时间"
                  >
                    <SvgIcon icon="editdata"></SvgIcon>
                  </button>
                  <button
                    type="button"
                    style={{
                      background: 'none',
                      border: 'none',
                      padding: '0',
                      cursor: 'pointer',
                      display: 'inline-flex',
                      alignItems: 'center',
                    }}
                    onClick={() => {
                      delCollectionMetadata('expiredTime');
                    }}
                    onKeyDown={(e) => {
                      if (e.key === 'Enter' || e.key === ' ') {
                        e.preventDefault();
                        delCollectionMetadata('expiredTime');
                      }
                    }}
                    aria-label="删除过期时间"
                  >
                    <SvgIcon icon="deledata"></SvgIcon>
                  </button>
                </div>
              </div>
              <div className="mt-2">
                {dayjs(metadata.expiredTime).format('YYYY-MM-DD HH:mm:ss')}
              </div>
            </div>
          )}
          {metas}
        </div>

        {/* <Descriptions column={1}>
          {metadata.expiredTime && (
            <Descriptions.Item label={'过期时间'}>
              {dayjs(metadata.expiredTime).format('YYYY-MM-DD HH:mm:ss')}
              <Button
                onClick={() => {
                  delCollectionMetadata('expiredTime');
                }}
                icon={<CloseOutlined style={{ fontSize: '8px' }} />}
                type="text"
                size="small"
              />
            </Descriptions.Item>
            
            
          )}
          {metas}
        </Descriptions> */}
      </div>

      {inputVisible && (
        <div className="flex flex-col gap-2">
          <div
            style={{
              width: '100%',
              backgroundColor: '#F2F3F5',
              padding: '10px',
              display: 'flex',
              flexDirection: 'column',
              borderRadius: '6px',
            }}
          >
            <div className="mb-2">
              <Select
                className="w-full"
                // size="small"
                value={metadataType}
                onChange={setMetadataType}
                options={[
                  {
                    label: '过期时间',
                    value: 'expiredTime',
                  },
                ]}
              ></Select>
            </div>

            {metadataType === 'expiredTime' && (
              <DatePicker
                onChange={(_, dataString) => {
                  onDateChange(`${dataString} 23:59:59`);
                }}
                allowClear={false}
                placeholder="请选择过期时间"
                disabledDate={(current) => {
                  return current && current < dayjs(undefined).endOf('day');
                }}
              />
            )}

            {metadataType === 'kv' && (
              <div>
                <Input
                  // className="metadata-input w-auto"
                  ref={inputKeyRef}
                  type="text"
                  // size="small"
                  placeholder="key"
                  value={inputKey}
                  onChange={handleInputKeyChange}
                />
                <Input
                  style={{ marginTop: '10px' }}
                  ref={inputRef}
                  type="text"
                  // size="small"
                  placeholder="value"
                  value={inputValue}
                  onChange={handleInputChange}
                />
              </div>
            )}

            <div
              style={{
                marginTop: '10px',
                display: 'flex',
                justifyContent: 'center',
                color: '#1B6DFA',
              }}
            >
              <div
                style={{
                  cursor: 'pointer',
                  display: 'flex',
                  alignItems: 'center',
                  marginRight: '8px',
                }}
                onClick={handleConfirm}
              >
                <SvgIcon icon="datasure"></SvgIcon>
                确认
              </div>
              <div
                className="mr-4"
                style={{ cursor: 'pointer', display: 'flex', alignItems: 'center' }}
                onClick={hideInput}
              >
                <SvgIcon icon="undatasure"></SvgIcon>
                取消
              </div>
            </div>
          </div>
          {/* <Descriptions column={1}>
            <Descriptions.Item label="元数据类型">
              <Select
                className="w-full"
                size="small"
                value={metadataType}
                onChange={setMetadataType}
                options={[
                  {
                    label: 'key-value',
                    value: 'kv',
                  },
                  {
                    label: '过期时间',
                    value: 'expiredTime',
                  },
                ]}
              ></Select>
            </Descriptions.Item>
            {metadataType === 'kv' && (
              <>
                <Descriptions.Item label="key">
                  <Input
                    className="metadata-input w-auto"
                    ref={inputKeyRef}
                    type="text"
                    size="small"
                    placeholder="key"
                    value={inputKey}
                    onChange={handleInputKeyChange}
                  />
                </Descriptions.Item>
                <Descriptions.Item label="value">
                  <Input
                    className="metadata-input w-auto"
                    ref={inputRef}
                    type="text"
                    size="small"
                    placeholder="value"
                    value={inputValue}
                    onChange={handleInputChange}
                  />
                </Descriptions.Item>
              </>
            )}
          </Descriptions> */}
          {/* {metadataType === 'expiredTime' && (
            <DatePicker
              onChange={(_, dataString) => {
                onDateChange(`${dataString} 23:59:59`);
              }}
              allowClear={false}
              placeholder="请选择过期时间"
            />
          )}
          <div className="ml-auto flex gap-2">
            <Button type="text" onClick={hideInput}>
              取消
            </Button>
            <Button type="text" onClick={handleConfirm}>
              确认
            </Button>
          </div> */}
        </div>
      )}
      {!inputVisible && (
        <Button icon={<PlusOutlined />} onClick={showInput} type="text">
          新建/修改元数据
        </Button>
      )}
    </>
  );
};

export default memo(Metadatas);
